﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExtBusiness.Struct;
using ExtBusiness.Admin;
using ExtBusiness;
using System.Data;
using System.Web.UI.HtmlControls;
using WF_Business;

/// <summary>
/// Summary description for edituser.
/// </summary>
public partial class SystemManager_EditUser : PageBase
{
    private Department depObj = new Department();
    public string type = string.Empty;
    private ExtBusiness.User.DepartHandle DepartHandle = new ExtBusiness.User.DepartHandle();

    #region 窗体加载
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!IsPostBack)
        {
            deleteUserAndGroup();
            InitState();
            try
            {
                string userId = Request["userid"];
                BindDepartmentInfo();

                ShowUserRoles();

                BindUserRole(userId);
                type = Request["type"];
            }
            catch (Exception ex)
            {
                msgAppear.Text = ex.Message;
            }
        }
    }
    #endregion
      
    #region 绑定单位及部门
    private void BindCompanyList()
    {
        DataTable dtSubDep = depObj.GetSubDepList(Request["userid"]);
        for (int i = 0; i < dtSubDep.Rows.Count; i++)
        {
            HtmlTableRow trTemp = this.FindControl("tr" + i.ToString()) as HtmlTableRow;
            trTemp.Visible = true;
            string strCompId = depObj.GetParentDepId(dtSubDep.Rows[i]["order_id"].ToString());
            DropDownList ddlComp = this.FindControl("ddlCompany" + i.ToString()) as DropDownList;
            BindCompList(ddlComp);
            ddlComp.SelectedValue = strCompId;
            DropDownList ddlDep = this.FindControl("ddlDepartment" + i.ToString()) as DropDownList;
            CompanyChange(strCompId, ddlDep);
            ddlDep.SelectedValue = dtSubDep.Rows[i]["order_id"].ToString();
        }
    }
    #endregion

    #region 获取用户和部门信息
    public void BindDepartmentInfo()
    {
        //获取用户信息
        String userId = Request["userid"];
        if (!string.IsNullOrEmpty(userId))  //编辑
        {
            UserStruct userInfo = ExtBusiness.Admin.User.GetUserById(userId);
            txtLoginName.Text = userInfo.UserName;
            txtRealName.Text = userInfo.UserRealName;
            txtOrderbyid.Text = userInfo.UserOderbyid;
            txtMobile.Text = userInfo.UserMobile;
            txtNewPass.Text = userInfo.UserPass;
            txtNewPassAgain.Text = userInfo.UserPass;

            BindCompanyList(); //绑定部门

        }
        else           //新增
        {
            tr0.Visible = true;
            BindCompList(ddlCompany0);
            ddlCompany0.SelectedIndex = 0;
            CompanyChange(ddlCompany0.SelectedValue, ddlDepartment0);
            ddlDepartment0.SelectedIndex = 0;
        }
    }
    #endregion

    #region 修改用户信息/添加用户
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        type = Request["type"];
        if (txtNewPass.Text.CompareTo(txtNewPassAgain.Text) == 0)
        {
            try
            {
                UserStruct userInfo = new UserStruct();

                userInfo.UserId = Request["userid"];
                userInfo.UserName = txtLoginName.Text;
                userInfo.UserRealName = txtRealName.Text;
                userInfo.UserOderbyid = txtOrderbyid.Text;
                userInfo.UserPass = txtNewPass.Text;
                userInfo.UserMobile = txtMobile.Text;
                userInfo.UserInvalid = ddlInvalid.SelectedValue;

                string strDepId = string.Empty;
                for (int i = 0; i < 5; i++)
                {
                    HtmlTableRow trTemp = this.FindControl("tr" + i.ToString()) as HtmlTableRow;
                    DropDownList ddlDep = this.FindControl("ddlDepartment" + i.ToString()) as DropDownList;
                    if (trTemp.Visible && !string.IsNullOrEmpty(ddlDep.SelectedValue))
                    {
                        strDepId = strDepId + ddlDep.SelectedValue + ",";
                    }
                }
                strDepId = strDepId.TrimEnd(',');
                userInfo.UserDepartId = strDepId.Split(',');

                if (!string.IsNullOrEmpty(userInfo.UserId))
                {
                    if (userDepartment(userInfo.UserId))
                    {
                        ExtBusiness.Admin.User.UpdateUserBasicInfo(userInfo);
                    }
                    else
                    {
                        ExtBusiness.Admin.User.UpdateUserById(userInfo);
                    }
                    AddUserOfficeTel(userInfo.UserId);
                    msgAppear.Text = "修改成功";
                }
                else
                {
                    userInfo.UserId = Guid.NewGuid().ToString();
                    ExtBusiness.Admin.User.AddNewUser(userInfo);
                    AddUserOfficeTel(userInfo.UserId);
                    msgAppear.Text = "添加成功";
                    if (type != "AddressBook")
                    {
                        Response.Redirect("openuserlist.aspx");
                    }
                    else
                    {
                        Response.Redirect("AddressBook.aspx");
                    }
                }

            }
            catch (Exception ex)
            {
                msgAppear.Text = ex.Message;
            }
        }
        else
        {
            msgAppear.Text = "两次输入的密码不一致！";
        }
    }

    #endregion

    #region 判断st_user_department是否变化
    protected bool userDepartment(string userID)
    {
        string strDepId = string.Empty;
        for (int i = 0; i < 5; i++)
        {
            HtmlTableRow trTemp = this.FindControl("tr" + i.ToString()) as HtmlTableRow;
            DropDownList ddlDep = this.FindControl("ddlDepartment" + i.ToString()) as DropDownList;
            if (trTemp.Visible && !string.IsNullOrEmpty(ddlDep.SelectedValue))
            {
                strDepId = strDepId + ddlDep.SelectedValue + ",";
            }
        }
        string strUserDepInfo = string.Empty;
        strUserDepInfo = ExtBusiness.Admin.User.UserDepartmentInfo(userID);
        if (strDepId != string.Empty && strDepId == strUserDepInfo)
        {
            return true;
        }
        else
        {
            return false;
        }



    }

    #endregion

    #region 添加选择列表
    protected void btnAddDepSel_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            HtmlTableRow trTemp = this.FindControl("tr" + i.ToString()) as HtmlTableRow;
            if (!trTemp.Visible)
            {
                trTemp.Visible = true;
                DropDownList ddlComp = this.FindControl("ddlCompany" + i.ToString()) as DropDownList;
                BindCompList(ddlComp);
                ddlComp.SelectedIndex = 0;
                DropDownList ddlDep = this.FindControl("ddlDepartment" + i.ToString()) as DropDownList;
                CompanyChange(ddlComp.SelectedValue, ddlDep);
                ddlDep.SelectedIndex = 0;
                break;
            }
        }
    }
    #endregion

    #region 删除选择列表
    protected void btnDel1_Click(object sender, EventArgs e)
    {
        DelSelList(tr1);
    }
    protected void btnDel2_Click(object sender, EventArgs e)
    {
        DelSelList(tr2);
    }
    protected void btnDel3_Click(object sender, EventArgs e)
    {
        DelSelList(tr3);
    }
    protected void btnDel4_Click(object sender, EventArgs e)
    {
        DelSelList(tr4);
    }
    #endregion

    #region 单位的selectedindexchanged事件
    protected void ddlCompany0_SelectedIndexChanged(object sender, EventArgs e)
    {
        CompanyChange(ddlCompany0.SelectedValue, ddlDepartment0);
    }
    protected void ddlCompany1_SelectedIndexChanged(object sender, EventArgs e)
    {
        CompanyChange(ddlCompany1.SelectedValue, ddlDepartment1);
    }
    protected void ddlCompany2_SelectedIndexChanged(object sender, EventArgs e)
    {
        CompanyChange(ddlCompany2.SelectedValue, ddlDepartment2);
    }
    protected void ddlCompany3_SelectedIndexChanged(object sender, EventArgs e)
    {
        CompanyChange(ddlCompany3.SelectedValue, ddlDepartment3);
    }
    protected void ddlCompany4_SelectedIndexChanged(object sender, EventArgs e)
    {
        CompanyChange(ddlCompany4.SelectedValue, ddlDepartment4);
    }
    #endregion

    /// <summary>
    /// 获取用户的状态信息，用于显示！
    /// </summary>
    private void InitState()
    {
        UserStruct userState = ExtBusiness.Admin.User.GetUserById(Request["userid"]);
        ddlInvalid.SelectedValue = userState.UserInvalid;
    }

    /// <summary>
    /// 根据选择的单位绑定部门
    /// </summary>
    /// <param name="SelComp">所选择的单位id</param>
    /// <param name="DepList">对应的部门dropdownlist</param>
    private void CompanyChange(string SelComp, DropDownList DepList)
    {
        try
        {

            DataTable dtbumen;

            dtbumen = DepartHandle.GetDepartmentByParentId(SelComp);


            DepList.Items.Clear();
            if (dtbumen.Rows.Count > 0)
            {
                DepList.DataSource = dtbumen;
                DepList.DataTextField = "depart_name";
                DepList.DataValueField = "departid";
                DepList.DataBind();
            }
            else
            {
                DataTable dtDedepart;

                dtDedepart = DepartHandle.GetDepartmentParId(SelComp);

                DepList.DataSource = dtDedepart;
                DepList.DataTextField = "depart_name";
                DepList.DataValueField = "departid";
                DepList.DataBind();
            }
        }
        catch (Exception ex)
        {
            msgAppear.Text = ex.Message;
        }
    }

    /// <summary>
    /// 绑定单位列表
    /// </summary>
    /// <param name="CompList"></param>
    private void BindCompList(DropDownList CompList)
    {
        DataTable dtdw = depObj.GetDepartment();
        if (dtdw.Rows.Count > 0)
        {
            CompList.DataSource = dtdw;
            CompList.DataTextField = "depart_name";
            CompList.DataValueField = "departid";
            CompList.DataBind();
        }
    }

    /// <summary>
    /// 点击删除时隐藏tr
    /// </summary>
    /// <param name="tr">要隐藏的tr</param>
    private void DelSelList(HtmlTableRow tr)
    {
        tr.Visible = false;
    }

    protected void BindUserRole(string userid)
    {
        DataTable dt;
        dt = ExtBusiness.User.UserGroupHandle.GetUserGroupById(userid);

        ShowUserRoleLab(userid);
        BindOfficeTel(userid);
    }

    protected void ShowUserRoleLab(string userid)
    {
        DataTable dt;
        dt = ExtBusiness.User.UserGroupHandle.GetGroupName(userid);
        if (dt.Rows.Count > 0)
        {
            string nRole = string.Empty;
            foreach (System.Data.DataRow drTemp in dt.Rows)
            {
                nRole += drTemp["group_name"].ToString() + "<span style='color: #003300'><strong>|</strong></span>";
            }
            if (!string.IsNullOrEmpty(nRole))
            {
                this.labRole.Text = "<span style='color: #003300'><strong>用户所属角色：</strong></span>" + nRole.Remove(nRole.Length - 54, 54);
            }
            else
            {
                this.labRole.Text = "该用户还未配置任何角色";
            }
        }

    }

    //更新人员办公室电话与分机号        
    protected void AddUserOfficeTel(string userid)
    {
        string OfficeTel = txtOfficeTel.Text.Trim();
        string ExtNo = txtExtNo.Text.Trim();
        String HouseTel = txtHouseTel.Text.Trim();


        ExtBusiness.User.UserHandle User = new ExtBusiness.User.UserHandle();
        User.UpdateUser(OfficeTel, ExtNo, UserId, HouseTel);
    }
    //绑定人员办公室电话
    protected void BindOfficeTel(string userid)
    {
        DataTable dtTemp = new DataTable();
        ExtBusiness.User.UserHandle User = new ExtBusiness.User.UserHandle();
        dtTemp = User.GetUserInfo(userid);
        if (dtTemp.Rows.Count > 0)
        {
            txtExtNo.Text = dtTemp.Rows[0]["EXTNO"].ToString();
            txtOfficeTel.Text = dtTemp.Rows[0]["OFFICETEL"].ToString();
            txtHouseTel.Text = dtTemp.Rows[0]["HOUSETEL"].ToString();
        }
    }

    /// <summary>
    ///获取绑定用户
    /// </summary>
    /// <param name="userid"></param>
    protected void ShowUserRoles()
    {
        string strUserid = Request["userid"];
        string strSql = string.Format(@"select a.group_name,a.groupid,b.userid from st_group a ,st_user_group b 
                where a.groupid=b.gid and userid='{0}'", strUserid);
        DataTable dt;
        SysParams.OAConnection().RunSql(strSql, out dt);
        gridview.DataSource = dt;
        gridview.RecordCount = dt.Rows.Count;
        gridview.DataBind();
    }

    /// <summary>
    /// 删除角色和用户对应关系
    /// </summary>
    protected void deleteUserAndGroup()
    {
        string strUserId = Request["userid"];
        string strGroupId = Request["gid"];

        if (!string.IsNullOrEmpty(strGroupId))
        {
            string strSql = string.Format(@"delete from st_user_group a 
                where a.gid='{0}' and userid='{1}'", strGroupId, strUserId);

            SysParams.OAConnection().RunSql(strSql);
        }
    }


    /// <summary>
    /// grid行绑定事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gridview_RowCreated(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
                break;
            case DataControlRowType.DataRow:
                if (e.Row.DataItem == null)
                {
                    break;
                }

                DataRowView drvTemp = e.Row.DataItem as DataRowView;
                HyperLink hlink = e.Row.FindControl("hlDelete") as HyperLink;
                if (hlink != null && drvTemp != null)
                {
                    hlink.NavigateUrl = string.Format("edituser.aspx?gid={0}&userid={1}",
                        drvTemp["groupid"], drvTemp["userid"]);
                }
                break;
        }

    }

    /// <summary>
    /// grid加载事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gridview_OnLoadData(object sender, EventArgs e)
    {
        ShowUserRoles();
    }

}
